package net.vkits.api;

import io.jsonwebtoken.Claims;
import net.vkits.common.dto.BaseDTO;
import net.vkits.common.exceptions.DuplicatePhoneExeption;
import net.vkits.common.exceptions.NoSuchVerifyCode;
import net.vkits.common.exceptions.TooManyTimesException;
import net.vkits.common.filter.JwtHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ethan-liu on 2017/2/2.
 */
@RestControllerAdvice(basePackages = "net.vkits.api")
public class BaseApiController extends ResponseEntityExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(BaseApiController.class);

    @ModelAttribute
    public void setRespJwtHeader(HttpServletRequest request, HttpServletResponse response) {
        final String path = request.getServletPath();
        if (request.getServletPath().equals("/api/v2/banners") ||
                request.getServletPath().equals("/api/v2/contents") ||
                request.getServletPath().equals("/api/v2/posts/list") ||
                request.getServletPath().contains("detail") ||
                request.getServletPath().equals("/api/v2/qas") ) {
            return;
        }
        if (!path.contains("smscode") && !path.contains("login")) {
            final Claims claims = (Claims) request.getAttribute("claims");
            String cellphone = claims.get("phone").toString();
            response.setHeader("Authorization", JwtHelper.createJWT(cellphone));
        }
    }

    @ExceptionHandler(value = {TooManyTimesException.class, NoSuchVerifyCode.class, DuplicatePhoneExeption.class})
    public ResponseEntity<?> knownExceptionHandler(HttpServletRequest request, RuntimeException ex) {
        logger.error("---KnownException Handler---Host {} invokes url {} method {} ERROR: {}", request.getRemoteHost(), request.getRequestURL(), request.getMethod(), ex.getMessage());
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(new BaseDTO(status.value(), ex.getMessage()), status);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<?> defaultExceptionHandler(HttpServletRequest request, Exception ex) {
        logger.error("---DefaultException Handler---Host {} invokes url {} method {} ERROR: ", request.getRemoteHost(), request.getRequestURL(), request.getMethod(), ex);
        HttpStatus status = getStatus(request);
        return new ResponseEntity<>(new BaseDTO(status.value()), status);
    }



    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
